package com.atguigu.tingshu.user.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;

/**
 * Description:
 *
 * @author Yanxinhao on 2025/1/13
 */
@Configuration
@EnableConfigurationProperties(wxMaProperties.class)
public class wxMaConfiguration {
    @Autowired
    private wxMaProperties properties;

    /**
     * 用于注册一个微信小程序的service实例
     * @return
     */
    @Bean
    public WxMaService wxMaService(){
        //1.创建我们需要返回的具体实例-->WxMaServiceImpl
        WxMaService wxMaService = new WxMaServiceImpl();
        //2.创建WxMaConfig对象，用于配置微信小程序的appid和secret
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        //3.设置appid和secret
        config.setAppid(properties.getAppId());
        config.setSecret(properties.getAppSecret());
        //4.将配置应用于返回实例中
        wxMaService.setWxMaConfig(config);
        return wxMaService;
    }


    /**
     * 用于注册一个RSA私钥的signer对象
     * @return
     */
    @Bean
    public RsaSigner rsaSigner(){
        //1.获取resource目录下的指定jks证书文件
        ClassPathResource jks = new ClassPathResource("tingshu.jks");
        //2.获取钥匙工厂对象 -- (第一个参数是jks文件，第二个参数是密码)
        KeyStoreKeyFactory keyFactory = new KeyStoreKeyFactory(jks, "tingshu".toCharArray());
        //3.根据钥匙工厂对象，获取对应的钥匙串
        KeyPair keyPair = keyFactory.getKeyPair("tingshu", "tingshu".toCharArray());
        //4.根据钥匙串对象，获取私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        //5.返回这个RSA私钥
        return new RsaSigner(privateKey);
    }
}